import React, { useState } from 'react';
import katex from 'katex';
import 'katex/dist/katex.min.css';

const Demo = () => {
  const [formula, setFormula] = useState("\\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}");
  
  const handleFormulaChange = (e) => {
    setFormula(e.target.value);
  };

  const renderLatex = () => {
    try {
      return katex.renderToString(formula, { 
        displayMode: true,
        throwOnError: false
      });
    } catch (error) {
      return '语法错误';
    }
  };
  
  return (
    <div className="py-20 bg-white">
      <div className="container mx-auto px-6">
        <h2 className="text-3xl font-bold text-center mb-16">实时预览效果</h2>
        <div className="grid md:grid-cols-2 gap-8">
          <div className="bg-gray-900 p-6 rounded-xl">
            <textarea
              className="w-full h-32 bg-gray-800 text-white font-mono p-4 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={formula}
              onChange={handleFormulaChange}
              placeholder="输入 LaTeX 公式..."
            />
            <div className="mt-4 text-gray-400 text-sm">
              提示：尝试修改公式，预览将实时更新
            </div>
          </div>
          <div className="bg-white p-6 rounded-xl shadow-lg flex items-center justify-center min-h-[8rem]">
            <div 
              dangerouslySetInnerHTML={{ 
                __html: renderLatex()
              }} 
            />
          </div>
        </div>
        <div className="mt-8 text-center text-gray-600">
          <p>支持所有标准的 LaTeX 数学公式语法</p>
          <p className="text-sm mt-2">例如：\int, \sum, \frac, \sqrt 等</p>
        </div>
      </div>
    </div>
  );
};

export default Demo;